//
//  UIImageView+Ex.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//
import Kingfisher

public extension AnimatedImageView {
    
    public func setImageURLString(_ urlString:String?,cacheType:TSKFImageCacheType? = nil,completion: ((Bool) -> Void)? = nil){
        guard let urlString = urlString,let url = URL(string: urlString) else {
            setImageNil()
            return
        }
        setImageResource(url, cacheType: cacheType)
    }
    
    public func setImageResource(_ resource:Resource?,cacheType:TSKFImageCacheType? = nil,completion: ((Bool) -> Void)? = nil){
        var options: KingfisherOptionsInfo = [.cacheOriginalImage]
        if let cacheType = cacheType {
            options.append(.targetCache(cacheType.imageCache))
        }
        
        kf.setImage(with: resource, options: options){ [weak self] result in
            guard let self = self else { return }
            switch result {
            case .success(_):
                self.startAnimating()
                completion?(true)
            case .failure(let error):
                self.setImageNil()
                print("加载失败: \(error.localizedDescription)")
                completion?(false)
            }
          
        }
    }
    
    func setImageNil(){
        let resource:Resource? = nil
        kf.setImage(with: resource)
    }
}


class TSCustomActivityIndicator: Indicator {
    let activityIndicator = UIActivityIndicatorView(style: .medium)
    
    init(color: UIColor) {
        activityIndicator.color = color
    }
    
    func startAnimatingView() {
        activityIndicator.startAnimating()
    }
    
    func stopAnimatingView() {
        activityIndicator.stopAnimating()
    }
    
    var view: IndicatorView {
        return activityIndicator
    }
}

public extension UIImageView {
    
    static var kfTargetCache:ImageCache? = nil

    /// 创建并配置 UIImageView
    /// - Parameters:
    ///   - imageName: 图片名称
    ///   - contentMode: 内容模式，默认为 `.scaleAspectFit`
    ///   - backgroundColor: 背景颜色，默认为透明
    /// - Returns: 配置完成的 UIImageView 实例
    static public func createImageView(
                                image:UIImage? = nil,
                                imageName: String? = nil,
                                contentMode: UIView.ContentMode = .scaleAspectFit,
                                backgroundColor: UIColor = .clear,
                                corner: CGFloat? = nil,
                                autoMirrored: Bool = true
    ) -> UIImageView {
        let imageView = UIImageView()
                                    
        if let image = image{
            imageView.image = image
        }

        if let imageName = imageName ,imageName.count > 0 {
            imageView.image = UIImage(named: imageName)
        }
        
        if let image = imageView.image,autoMirrored{
            imageView.image = image.mirrored
        }
        
        imageView.contentMode = contentMode
        imageView.backgroundColor = backgroundColor
        
        if let corner = corner {
            imageView.cornerRadius = corner
        }else{
            imageView.clipsToBounds = true
        }
        
        return imageView
    }
    
    /// 异步创建并加载图片的 UIImageView
    /// - Parameters:
    ///   - imageName: 本地占位图片名称
    ///   - urlString: 图片的 URL 字符串
    ///   - contentMode: 内容模式，默认为 `.scaleAspectFit`
    ///   - backgroundColor: 背景颜色，默认为透明
    ///   - showLoading: 是否显示加载动画，默认为 `true`
    ///   - completion: 图片加载成功后的回调
    static public func createAsyncImageView(urlString: String?,
                                     placeholder:UIImage?,
                                     contentMode: UIView.ContentMode = .scaleAspectFit,
                                        adaptiveMode:Bool = false,
                                     backgroundColor: UIColor = .clear,
                                     showLoading: Bool = false,
                                    progressBlock: ((Float)->Void)? = nil,
                                     completion: ((UIImage?) -> Void)? = nil) -> UIImageView {
        let imageView = UIImageView()
        imageView.setAsyncImage(urlString: urlString,
                                placeholder:placeholder,
                                contentMode:contentMode,
                                adaptiveMode:adaptiveMode,
                                backgroundColor:backgroundColor,
                                showLoading:showLoading,
                                progressBlock:progressBlock,
                                completion:completion)
        return imageView
    }

    public func setAsyncImage(urlString: String?,
                     placeholder: UIImage? = nil,
                     contentMode: UIView.ContentMode? = nil,
                 adaptiveMode:Bool = false,
                 backgroundColor: UIColor? = nil,
                      showLoading: Bool = false,
                        cacheType:TSKFImageCacheType? = nil,
                        progressBlock: ((Float)->Void)? = nil,
                      completion: ((UIImage?) -> Void)? = nil){
        let imageView = self
        
        if let contentMode = contentMode {
            imageView.contentMode = contentMode
        }
        
        if let backgroundColor = backgroundColor {
            imageView.backgroundColor = backgroundColor
        }
 
        imageView.image = placeholder
        
        guard let urlString = urlString else {
            completion?(nil)
            return
        }
      
        if urlString.count == 0 {
            completion?(nil)
            return
        }
        
        if urlString.contains("http") {
            guard let url = URL(string: urlString) else {
                completion?(nil)
                return
            }
            
            kf.indicatorType = showLoading ? .custom(indicator: TSCustomActivityIndicator(color: .white)) : .none
            var options: KingfisherOptionsInfo = []
            if let cacheType = cacheType {
                options.append(.targetCache(cacheType.imageCache))
            }else if let kfTargetCache = Self.kfTargetCache {
                options.append(.targetCache(kfTargetCache))
            }
            
            imageView.kf.setImage(with: url,
                 placeholder: placeholder,
                     options: options,
                progressBlock: { receivedSize, totalSize in
                let progress = receivedSize/totalSize
                progressBlock?(Float(progress))
            }){ result in
                
                if let image = try? result.get().image {
                    kMainAsync {
                        completion?(image)
                    }
                }else{
                    completion?(nil)
                }
            }
            
        }else if urlString.contains("/") {
            imageView.image = UIImage(contentsOfFile: urlString)
            completion?(imageView.image)
        }else {
            if let image = UIImage(named: urlString) {
                imageView.image = image
                completion?(image)
            }
        }
    }

}

public extension UIImageView {
    
    static public func createRightArrow() -> UIImageView {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "right_arrow")?.mirrored
        return imageView
    }
    
    /// 根据图片比例自动选择最佳缩放模式
    public func adaptiveScale() {
//        guard let image = image else { return }
//        
//        let viewSize = bounds.size
//        let imageRatio = image.size.width / image.size.height
//        let viewRatio = viewSize.width / viewSize.height
//        
//        let contentNewMode:UIView.ContentMode = imageRatio > viewRatio ? .scaleAspectFill : .scaleAspectFit
//        self.contentMode = contentNewMode
//        
//        dePrint("UIImageView.adaptiveScale contentMode =\(contentNewMode)")
    }
}

public extension UIImageView {
    public func setImage(_ image: UIImage?, duration: CFTimeInterval = 0.2, animated: Bool = true) {
        if let image = image {
            if animated {
                UIView.transition(
                    with: self,
                    duration: duration,
                    options: [.transitionCrossDissolve, .curveEaseInOut, .allowUserInteraction]
                ) {
                    self.image = image
                }
            }else {
                self.image = image
            }
        }
    }
}
